package com.jzo2o.market.handler;

import com.jzo2o.api.customer.CommonUserApi;
import com.jzo2o.api.customer.dto.response.CommonUserResDTO;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.redis.handler.SyncProcessHandler;
import com.jzo2o.redis.model.SyncMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.jzo2o.market.constants.RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME;

//Bean的名字编写规则 
// 队列名称：QUEUE:COUPON:SEIZE:SYNC:{8},把开头部分（QUEUE:）和序号部分（:{8}）去掉。
// 截取后为：COUPON:SEIZE:SYNC
@Component(COUPON_SEIZE_SYNC_QUEUE_NAME)
@Slf4j
public class SeizeCouponSyncProcessHandler implements SyncProcessHandler<Object> {
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private CommonUserApi commonUserApi;

    @Autowired
    private CouponMapper couponMapper;

    @Override
    public void batchProcess(List<SyncMessage<Object>> multiData) {
        throw new RuntimeException("不支持批量处理");
    }

    @Override
    public void singleProcess(SyncMessage<Object> singleData) {
        log.info("获取要同步抢券结果数据： {}", singleData);
        long userId = NumberUtils.parseLong(singleData.getKey());//用户id
        long activityId = NumberUtils.parseLong(singleData.getValue().toString());//活动id

        log.info("userId={},activity={}", userId, activityId);

        //todo: 向优惠券表插入数据

        //获取活动信息
        Activity activity = activityMapper.selectById(activityId);

        //获取用户信息(这里需要调用远程微服务)
        CommonUserResDTO userResDTO = commonUserApi.findById(userId);


        Coupon coupon = new Coupon();
        coupon// 设置优惠券ID
                .setName(activity.getName()) // 设置优惠券名称
                .setUserId(userId) // 设置用户ID
                .setUserName(activity.getName()) // 设置用户名
                .setUserPhone(userResDTO.getPhone()) // 设置用户手机号
                .setActivityId(activityId) // 设置活动ID
                .setType(activity.getType()) // 设置使用类型（满减或折扣）
                .setDiscountRate(activity.getDiscountRate()) // 设置折扣率
                .setDiscountAmount(activity.getDiscountAmount()) // 设置优惠金额
                .setAmountCondition(activity.getAmountCondition()) // 设置满减条件金额
                .setValidityTime(LocalDateTime.now().plusDays(activity.getValidityDays())) // 设置有效期(当前时间+优惠券的有效时间 天)
                .setStatus(1) // 设置状态（未使用/已使用/已过期）
                .setCreateTime(activity.getCreateTime()) // 设置创建时间
                .setUpdateTime(activity.getUpdateTime()); // 设置更新时间
        couponMapper.insert(coupon);

        //todo：扣减数据库表中的库存
        //updata activity set stock_num where id=活动id and stock_num > 0;
        int i = activityMapper.deductStock(activityId);
        if(i==0)
        {
            throw new RuntimeException("同步失败");
        }

    }
}